# Computations
import pandas as pd
import numpy as np
# Visualisation libraries
## Text
from colorama import Fore, Back, Style
from IPython.display import Image, display, Markdown, Latex, clear_output
## plotly
from plotly.offline import init_notebook_mode, iplot
import plotly.graph_objs as go
import plotly.offline as py
from plotly.subplots import make_subplots
import plotly.express as px
## seaborn
import seaborn as sns
## matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Polygon
from matplotlib.font_manager import FontProperties
import matplotlib.colors as mcolors
plt.style.use('seaborn-whitegrid')
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
plt.rcParams['text.color'] = 'k'
%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
In this article, we work on a dataset available from the UCI Machine Learning Repository. The data is related to direct marketing campaigns (phone calls) of a Portuguese banking institution. The classification goal is to predict if the client will subscribe to a term deposit (variable y).
This dataset is based on "Bank Marketing" UCI dataset (please check the description at archive.ics.uci.edu/ml/datasets/Bank+Marketing). The data is enriched by the addition of five new social and economic features/attributes (national wide indicators from a ~10M population country), published by the Banco de Portugal and publicly available at: bportugal.pt/estatisticasweb. This dataset is almost identical to the one used in [Moro et al., 2014] (it does not include all attributes due to privacy concerns).
The data is related to the direct marketing campaigns of a Portuguese banking institution. The marketing campaigns were based on phone calls. Often, more than one contact to the same client was required, in order to access if the product (bank term deposit) would be ('yes') or not ('no') subscribed.
There are four datasets:
The classification goal is to predict if the client will subscribe (yes/no) a term deposit (variable y).
The zip file includes two datasets:
The binary classification goal is to predict if the client will subscribe a bank term deposit (variable y).
Data = pd.read_csv('Data/bank-additional-full_EDA.csv')
display(Data.head(10).style.hide_index().set_precision(2))
Target = 'Term Deposit Subscription'
Labels = ['No', 'Yes']
| Age | Job | Marital | Education | Default | Housing | Loan | Contact | Month | Day Of Week | Duration | Campaign | Pdays | Previous | Poutcome | Employment Variation Rate | Consumer Price Index | Consumer Confidence Index | Euribor three Month Rate | Number of Employees | Term Deposit Subscription |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 56 | Housemaid | Married | Basic 4Y | No | No | No | Telephone | May | Monday | 261 | 1 | 999 | 0 | Nonexistent | 1.10 | 93.99 | -36.40 | 4.86 | 5191.00 | No |
| 57 | Services | Married | High School | Unknown | No | No | Telephone | May | Monday | 149 | 1 | 999 | 0 | Nonexistent | 1.10 | 93.99 | -36.40 | 4.86 | 5191.00 | No |
| 37 | Services | Married | High School | No | Yes | No | Telephone | May | Monday | 226 | 1 | 999 | 0 | Nonexistent | 1.10 | 93.99 | -36.40 | 4.86 | 5191.00 | No |
| 40 | Admin. | Married | Basic 6Y | No | No | No | Telephone | May | Monday | 151 | 1 | 999 | 0 | Nonexistent | 1.10 | 93.99 | -36.40 | 4.86 | 5191.00 | No |
| 56 | Services | Married | High School | No | No | Yes | Telephone | May | Monday | 307 | 1 | 999 | 0 | Nonexistent | 1.10 | 93.99 | -36.40 | 4.86 | 5191.00 | No |
| 45 | Services | Married | Basic 9Y | Unknown | No | No | Telephone | May | Monday | 198 | 1 | 999 | 0 | Nonexistent | 1.10 | 93.99 | -36.40 | 4.86 | 5191.00 | No |
| 59 | Admin. | Married | Professional Course | No | No | No | Telephone | May | Monday | 139 | 1 | 999 | 0 | Nonexistent | 1.10 | 93.99 | -36.40 | 4.86 | 5191.00 | No |
| 41 | Blue-Collar | Married | Unknown | Unknown | No | No | Telephone | May | Monday | 217 | 1 | 999 | 0 | Nonexistent | 1.10 | 93.99 | -36.40 | 4.86 | 5191.00 | No |
| 24 | Technician | Single | Professional Course | No | Yes | No | Telephone | May | Monday | 380 | 1 | 999 | 0 | Nonexistent | 1.10 | 93.99 | -36.40 | 4.86 | 5191.00 | No |
| 25 | Services | Single | High School | No | Yes | No | Telephone | May | Monday | 50 | 1 | 999 | 0 | Nonexistent | 1.10 | 93.99 | -36.40 | 4.86 | 5191.00 | No |
| Number of Instances | Number of Attributes |
|---|---|
| 41188 | 21 |
| Feature | Description |
|---|---|
| Age | numeric |
| Job | Type of Job (categorical: "admin.","blue-collar","entrepreneur","housemaid","management","retired","self-employed","services","student","technician","unemployed","unknown") |
| Marital | marital status (categorical: "divorced","married","single","unknown"; note: "divorced" means divorced or widowed) |
| Education | (categorical: "basic.4y","basic.6y","basic.9y","high.school","illiterate","professional.course","university.degree","unknown") |
| Default | has credit in default? (categorical: "no","yes","unknown") |
| Housing | has housing loan? (categorical: "no","yes","unknown") |
| Loan | has personal loan? (categorical: "no","yes","unknown") |
| Feature | Description |
|---|---|
| Contact | contact communication type (categorical: "cellular","telephone") |
| Month | last contact month of year (categorical: "jan", "feb", "mar", ..., "nov", "dec") |
| Day of week | last contact day of the week (categorical: "mon","tue","wed","thu","fri") |
| Duration | last contact duration, in seconds (numeric). Important note: this attribute highly affects the output target (e.g., if duration=0 then y="no"). Yet, the duration is not known before a call is performed. Also, after the end of the call y is obviously known. Thus, this input should only be included for benchmark purposes and should be discarded if the intention is to have a realistic predictive model. |
| Feature | Description |
|---|---|
| Campaign | number of contacts performed during this campaign and for this client (numeric, includes last contact) |
| Pdays | number of days that passed by after the client was last contacted from a previous campaign (numeric; 999 means client was not previously contacted) |
| Previous | number of contacts performed before this campaign and for this client (numeric) |
| Poutcome | outcome of the previous marketing campaign (categorical: "failure","nonexistent","success") |
| Feature | Description |
|---|---|
| Employment Variation Rate | employment variation rate - quarterly indicator (numeric) |
| Consumer Price Index | consumer price index - monthly indicator (numeric) |
| Consumer Confidence Index | consumer confidence index - monthly indicator (numeric) |
| Euribor three Month Rate | euribor* 3 month rate - daily indicator (numeric) |
| Number of Employees | number of employees - quarterly indicator (numeric) |
* the basic rate of interest used in lending between banks on the European Union interbank market and also used as a reference for setting the interest rate on other loans.
| Feature | Description |
|---|---|
| Term Deposit Subscription | has the client Term Deposit Subscription? (binary: "yes","no") |
Dataset_Subcategories = {}
Dataset_Subcategories['Bank Client Data'] = Data.iloc[:,:7].columns.tolist()
Dataset_Subcategories['Related with the Last Contact of the Current Campaign'] = Data.iloc[:,7:11].columns.tolist()
Dataset_Subcategories['Other Attributes'] = Data.iloc[:,11:15].columns.tolist()
Dataset_Subcategories['Social and Economic Context Attributes'] = Data.iloc[:,15:-1].columns.tolist()
Dataset_Subcategories['Output variable (Desired Target)'] = Data.iloc[:,-1:].columns.tolist()
def FeatAgg(Feat, ColorFeat, Target = Target, Inp = Data):
Out = Inp[[Feat, ColorFeat,Target]]
Out = Out.groupby([Feat, ColorFeat,Target])[Target].agg({'count'}).rename(columns = {'count':'Count'})
Out['Percentage'] = np.round(100* Out.values /Out.sum().values, 2)
Out.reset_index(drop = False, inplace = True)
Out = Out.sort_values(by=[Feat])
Out[Feat] = Out[Feat].astype(str)
return Out
def DistPlot(Feat, Target = Target, nbins = 20,
Colors = ['LightSalmon', 'LightBlue'], LC = 'Black',
yLim = [0, 80], H = 450, titleY = 0.92, Inp = Data):
fig = px.histogram(Inp, x = Feat, nbins=nbins, color= Target, marginal= 'box',
color_discrete_sequence= Colors, hover_data=Data.columns)
fig.update_xaxes(showline=True, linewidth=1, linecolor='Lightgray', mirror=True,
zeroline=False, zerolinewidth=1, zerolinecolor='Black',
showgrid=False, gridwidth=1, gridcolor='Lightgray')
fig.update_yaxes(showline=True, linewidth=1, linecolor='Lightgray', mirror=True,
zeroline=True, zerolinewidth=1, zerolinecolor='Black',
showgrid=True, gridwidth=1, gridcolor='Lightgray')
Name = '%s Distribution by %s' % (Target, Feat)
fig.update_layout(legend_orientation='v', plot_bgcolor= 'white', height= H, width= 980,
title={'text': '<b>' + Name + '<b>', 'x':0.5, 'y': titleY, 'xanchor': 'center', 'yanchor': 'top'},
yaxis_title='Frequency')
fig.update_traces(marker_line_color= LC, marker_line_width=0.5, opacity=1)
fig['layout']['yaxis'].update(range=yLim)
fig.show()
# For plotting
def FeatCut(Feat, ColorFeat, Bins, Target = Target, Inp = Data):
Out = Inp[[Feat, ColorFeat, Target]]
Out[Feat] = pd.cut(Out[Feat], bins = pd.IntervalIndex.from_tuples([(x, y) for x, y in zip(Bins[:-1],Bins[1:])]))
Out = Out.groupby([Feat, ColorFeat,Target])[Target].agg({'count'}).rename(columns = {'count':'Count'})
Out['Percentage'] = np.round(100* Out.values /Out.sum().values, 2)
Out.reset_index(drop = False, inplace = True)
Out = Out.sort_values(by=[Feat])
Out[Feat] = Out[Feat].astype(str)
return Out
def PlotX(df, Feat, ColorFeat, Target = Target,
Colors = list(mcolors.TABLEAU_COLORS.values()), LC = 'Black',
yLim = [0, 35], H = 500, titleY = 0.90):
# Figure
fig = make_subplots(rows=1, cols=2, horizontal_spacing = 0.02, shared_yaxes=True, y_title = 'Percent',
subplot_titles=('%s: <b>No<b>' % Target, '%s: <b>Yes<b>' % Target))
# Left
if Colors == None:
fig1 = px.bar(df.loc[df[Target] == 'No'], x= Feat, y= 'Percentage', orientation='v',
color = ColorFeat, text = 'Percentage', hover_data= df.columns)
else:
fig1 = px.bar(df.loc[df[Target] == 'No'], x= Feat, y= 'Percentage', orientation='v',
color = ColorFeat, text = 'Percentage', hover_data= df.columns,
color_discrete_sequence = Colors)
for i in range(len(fig1['data'])):
fig.add_trace(fig1['data'][i], row=1, col=1)
fig.update_traces(marker_line_color= LC, marker_line_width=1, opacity=1, row=1, col=1)
# Right
if Colors == None:
fig2 = px.bar(df.loc[df[Target] == 'Yes'], x= Feat, y= 'Percentage', orientation='v',
color = ColorFeat, text = 'Percentage', hover_data= df.columns)
else:
fig2 = px.bar(df.loc[df[Target] == 'Yes'], x= Feat, y= 'Percentage', orientation='v',
color = ColorFeat, text = 'Percentage', hover_data= df.columns,
color_discrete_sequence = Colors)
for i in range(len(fig2['data'])):
fig.add_trace(fig2['data'][i], row=1, col=2)
fig.update_traces(marker_line_color= LC, marker_line_width=1, opacity=1, showlegend = False, row=1, col=2)
# Update
fig.update_xaxes(showline=True, linewidth=1, linecolor='Lightgray', mirror=True,
zeroline=False, zerolinewidth=1, zerolinecolor='Black',
showgrid=False, gridwidth=1, gridcolor='Lightgray')
fig.update_yaxes(showline=True, linewidth=1, linecolor='Lightgray', mirror=True,
zeroline=False, zerolinewidth=1, zerolinecolor='Black',
showgrid=True, gridwidth=1, gridcolor='Lightgray', range= yLim)
fig.update_layout(legend_orientation='v', legend_title_text=ColorFeat, plot_bgcolor= 'white', height= H, width= 980)
fig.update_layout(legend=dict(font=dict(color="Black"), bordercolor="Lightgray", borderwidth=1))
Name = '%s Distribution by %s and %s' % (Feat, ColorFeat, Target)
fig.update_layout(title={'text': '<b>' + Name + '<b>', 'x':0.5, 'y': titleY, 'xanchor': 'center', 'yanchor': 'top'})
fig.show()
Feat = 'Age'
DistPlot(Feat, yLim = [0, int(1e4)], Colors = ['LightCoral', 'LawnGreen'])
Bins = [14, 24, 40, 59, 80, 100]
ColorFeat = 'Marital'
Table = FeatCut(Feat, ColorFeat, Bins)
PlotX(Table, Feat, ColorFeat, yLim = [0, 30])
ColorFeat = 'Default'
Table = FeatCut(Feat, ColorFeat, Bins)
PlotX(Table, Feat, ColorFeat, yLim = [0, 50], Colors = None)
ColorFeat = 'Housing'
Table = FeatCut(Feat, ColorFeat, Bins)
PlotX(Table, Feat, ColorFeat, yLim = [0, 30], Colors = None)
ColorFeat = 'Loan'
Table = FeatCut(Feat, ColorFeat, Bins)
PlotX(Table, Feat, ColorFeat, yLim = [0, 50], Colors = None)
ColorFeat = 'Contact'
Table = FeatCut(Feat, ColorFeat, Bins)
PlotX(Table, Feat, ColorFeat, yLim = [0, 35], Colors = None)
ColorFeat = 'Poutcome'
Table = FeatCut(Feat, ColorFeat, Bins)
PlotX(Table, Feat, ColorFeat, yLim = [0, 50], Colors = None)
del ColorFeat, Table, Bins
Feat = 'Job'
DistPlot(Feat, yLim = [0, int(1e4)], Colors = ['LightCoral', 'LawnGreen'])
ColorFeat = 'Marital'
Table = FeatAgg(Feat, ColorFeat)
PlotX(Table, Feat, ColorFeat, yLim = [0, 20], Colors = None)
ColorFeat = 'Default'
Table = FeatAgg(Feat, ColorFeat)
PlotX(Table, Feat, ColorFeat, yLim = [0, 20], Colors = None)
ColorFeat = 'Housing'
Table = FeatAgg(Feat, ColorFeat)
PlotX(Table, Feat, ColorFeat, yLim = [0, 14], Colors = None)
ColorFeat = 'Loan'
Table = FeatAgg(Feat, ColorFeat)
PlotX(Table, Feat, ColorFeat, yLim = [0, 20], Colors = None)
ColorFeat = 'Contact'
Table = FeatAgg(Feat, ColorFeat)
PlotX(Table, Feat, ColorFeat, yLim = [0, 15], Colors = None)
ColorFeat = 'Poutcome'
Table = FeatAgg(Feat, ColorFeat)
PlotX(Table, Feat, ColorFeat, yLim = [0, 20], Colors = None)
del ColorFeat, Table
Feat = 'Education'
DistPlot(Feat, yLim = [0, int(15e3)], Colors = ['LightCoral', 'LawnGreen'])
ColorFeat = 'Marital'
Table = FeatAgg(Feat, ColorFeat)
PlotX(Table, Feat, ColorFeat, yLim = [0, 14], Colors = None)
ColorFeat = 'Default'
Table = FeatAgg(Feat, ColorFeat)
PlotX(Table, Feat, ColorFeat, yLim = [0, 25], Colors = None)
ColorFeat = 'Housing'
Table = FeatAgg(Feat, ColorFeat)
PlotX(Table, Feat, ColorFeat, yLim = [0, 14], Colors = None)
ColorFeat = 'Loan'
Table = FeatAgg(Feat, ColorFeat)
PlotX(Table, Feat, ColorFeat, yLim = [0, 25], Colors = None)
ColorFeat = 'Contact'
Table = FeatAgg(Feat, ColorFeat)
PlotX(Table, Feat, ColorFeat, yLim = [0, 20], Colors = None)
ColorFeat = 'Poutcome'
Table = FeatAgg(Feat, ColorFeat)
PlotX(Table, Feat, ColorFeat, yLim = [0, 25], Colors = None)
del ColorFeat, Table
ColorFeat = 'Marital'
Table = FeatAgg(Feat, ColorFeat)
PlotX(Table, Feat, ColorFeat, yLim = [0, 14], Colors = None)
ColorFeat = 'Default'
Table = FeatAgg(Feat, ColorFeat)
PlotX(Table, Feat, ColorFeat, yLim = [0, 25], Colors = None)
ColorFeat = 'Loan'
Table = FeatAgg(Feat, ColorFeat)
PlotX(Table, Feat, ColorFeat, yLim = [0, 25], Colors = None)
ColorFeat = 'Contact'
Table = FeatAgg(Feat, ColorFeat)
PlotX(Table, Feat, ColorFeat, yLim = [0, 20], Colors = None)
ColorFeat = 'Poutcome'
Table = FeatAgg(Feat, ColorFeat)
PlotX(Table, Feat, ColorFeat, yLim = [0, 25], Colors = None)
del ColorFeat, Table
Feat = 'Campaign'
DistPlot(Feat, yLim = [0, int(4e4)], Colors = ['LightCoral', 'LawnGreen'], nbins = 15)
Bins = [0, 5, 10, 20, 50, 100]
ColorFeat = 'Marital'
Table = FeatCut(Feat, ColorFeat, Bins)
PlotX(Table, Feat, ColorFeat, yLim = [0, 50])
ColorFeat = 'Default'
Table = FeatCut(Feat, ColorFeat, Bins)
PlotX(Table, Feat, ColorFeat, yLim = [0, 70], Colors = None)
ColorFeat = 'Housing'
Table = FeatCut(Feat, ColorFeat, Bins)
PlotX(Table, Feat, ColorFeat, yLim = [0, 50], Colors = None)
ColorFeat = 'Loan'
Table = FeatCut(Feat, ColorFeat, Bins)
PlotX(Table, Feat, ColorFeat, yLim = [0, 80], Colors = None)
ColorFeat = 'Contact'
Table = FeatCut(Feat, ColorFeat, Bins)
PlotX(Table, Feat, ColorFeat, yLim = [0, 60], Colors = None)
ColorFeat = 'Poutcome'
Table = FeatCut(Feat, ColorFeat, Bins)
PlotX(Table, Feat, ColorFeat, yLim = [0, 80], Colors = None)
del ColorFeat, Table, Bins
Feat = 'Duration'
DistPlot(Feat, yLim = [0, int(4e4)], Colors = ['LightCoral', 'LawnGreen'])
Bins = [-1, 100, 200, 400, 800, 1000, 5000]
ColorFeat = 'Marital'
Table = FeatCut(Feat, ColorFeat, Bins).replace({'(-1, 100]':'[0, 100]'})
PlotX(Table, Feat, ColorFeat, yLim = [0, 20])
ColorFeat = 'Default'
Table = FeatCut(Feat, ColorFeat, Bins).replace({'(-1, 100]':'[0, 100]'})
PlotX(Table, Feat, ColorFeat, yLim = [0, 30], Colors = None)
ColorFeat = 'Housing'
Table = FeatCut(Feat, ColorFeat, Bins).replace({'(-1, 100]':'[0, 100]'})
PlotX(Table, Feat, ColorFeat, yLim = [0, 20], Colors = None)
ColorFeat = 'Loan'
Table = FeatCut(Feat, ColorFeat, Bins).replace({'(-1, 100]':'[0, 100]'})
PlotX(Table, Feat, ColorFeat, yLim = [0, 30], Colors = None)
ColorFeat = 'Contact'
Table = FeatCut(Feat, ColorFeat, Bins).replace({'(-1, 100]':'[0, 100]'})
PlotX(Table, Feat, ColorFeat, yLim = [0, 20], Colors = None)
ColorFeat = 'Poutcome'
Table = FeatCut(Feat, ColorFeat, Bins).replace({'(-1, 100]':'[0, 100]'})
PlotX(Table, Feat, ColorFeat, yLim = [0, 30], Colors = None)
del ColorFeat, Table, Bins
S. Moro, P. Cortez and P. Rita. A Data-Driven Approach to Predict the Success of Bank Telemarketing. Decision Support Systems, Elsevier, 62:22-31, June 2014
S. Moro, R. Laureano and P. Cortez. Using Data Mining for Bank Direct Marketing: An Application of the CRISP-DM Methodology. In P. Novais et al. (Eds.), Proceedings of the European Simulation and Modelling Conference - ESM'2011, pp. 117-121, Guimaraes, Portugal, October, 2011. EUROSIS. [bank.zip]